package com.openspring.platform.dao.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.openspring.framework.dao.AbstractSpringGenericDAO;
import com.openspring.framework.extend.spring.EntityPropertyRowMapper;
import com.openspring.platform.dao.DictionaryDAO;
import com.openspring.platform.model.Dictionary;

@Repository("dictionaryDAO")
public class DictionaryDAOImpl extends AbstractSpringGenericDAO<Dictionary, Long> implements DictionaryDAO {

	@Override
	public int deleteByDictId(Long dictId) {
		String sql = "DELETE FROM emp.t_platform_dictionary WHERE \"dictId\" = ?";
		return getJdbcTemplate().update(sql, dictId);
	}

	@Override
	public int[] batchDeleteByDictId(Long[] dictIds) {
		String sql = "DELETE FROM emp.t_platform_dictionary WHERE \"dictId\" = ?";
		List<Object[]> batch = new ArrayList<Object[]>();
        for(Long id : dictIds) {
            Object[] values = new Object[] {id};
            batch.add(values);
        }
        return getJdbcTemplate().batchUpdate(sql, batch);
	}

	@Override
	public List<Dictionary> queryByDictId(Long dictId) {
		String sql = "SELECT * FROM emp.t_platform_dictionary WHERE \"dictId\" = ? ORDER BY sort";
		return getJdbcTemplate().query(sql, new EntityPropertyRowMapper<Dictionary>(Dictionary.class), dictId);
	}

	@Override
	public List<Dictionary> queryByDictCode(String dictCode) {
		String sql = "SELECT * FROM emp.t_platform_dictionary WHERE \"dictId\" IN (SELECT id FROM emp.t_platform_dict WHERE code = ?) ORDER BY sort";
		return getJdbcTemplate().query(sql, new EntityPropertyRowMapper<Dictionary>(Dictionary.class), dictCode);
	}

	@Override
	public Dictionary getByDictCodeAndValue(String dictCode, String value) {
		String sql = "SELECT * FROM emp.t_platform_dictionary WHERE \"dictId\" = ? AND value = ?";
		List<Dictionary> entities = getJdbcTemplate().query(sql, new EntityPropertyRowMapper<Dictionary>(Dictionary.class), dictCode, value);
		return entities.isEmpty() ? null : entities.get(0);
	}
	
}
